package com.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class FileChannelExample {
	public static void main(String args[]) {
		Charset charset = Charset.forName("UTF-8");// Java.nio.charset.Charset处理了字符转换问题。它通过构造CharsetEncoder和CharsetDecoder将字符序列转换成字节和逆转换。
		CharsetDecoder decoder = charset.newDecoder();
		FileInputStream fis = null;
		try {
			ClassLoader classLoader = FileChannelExample.class.getClassLoader();
			/**
			 * getResource()方法会去classpath下找这个文件，获取到url resource,
			 * 得到这个资源后，调用url.getFile获取到 文件 的绝对路径
			 */
			URL url = classLoader.getResource("data/nio-data.txt");
			/**
			 * url.getFile() 得到这个文件的绝对路径
			 */
			System.out.println(url.getFile());
			fis = new FileInputStream(new File(url.getFile()));
			// fis = new FileInputStream("data/nio-data.txt");
			FileChannel fileChannel = fis.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
			CharBuffer charBuffer = CharBuffer.allocate(1024);
			int bytes = fileChannel.read(byteBuffer);
			while (bytes != -1) {
				byteBuffer.flip();
				decoder.decode(byteBuffer, charBuffer, false);
				charBuffer.flip();

				System.out.println(charBuffer);
				charBuffer.clear();
				byteBuffer.clear();
				bytes = fileChannel.read(byteBuffer);
			}
			if (fis != null) {
				fis.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}